﻿/**
* CRL
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Linq.Expressions;
using System.Collections;
using CRL.LambdaQuery;
using System.Runtime.InteropServices;
using CRL.Core;

namespace CRL
{
    public static partial class ExtensionMethod
    {
        public static void BeginTracking<T>(this T obj, Action<T> action) where T : class, new()
        {
            if (obj == null)
            {
                return;
            }
            var tracking = new ModelTracking(obj);
            action(obj);
            var table = TypeCache.GetTable(obj.GetType());
            var primaryKey = table.PrimaryKey;
            var keyValue = primaryKey.GetValue(obj);
            var modelKey = $"{table.Type}_{keyValue}";
            CallContext.SetData($"tracking_{modelKey}", tracking);
        }
        internal static ParameCollection GetTrackingDiff<T>(T obj)
        {
            var table = TypeCache.GetTable(obj.GetType());
            var primaryKey = table.PrimaryKey;
            var keyValue = primaryKey.GetValue(obj);
            var modelKey = $"{table.Type}_{keyValue}";
            var tracking = CallContext.GetData<ModelTracking>($"tracking_{modelKey}");
            return tracking?.GetDiff() ?? new ParameCollection();

        }
    }
}
